package com.he.security.config.annotation.web.reactive;

import com.he.security.web.reactive.result.AuthenticationPrincipalArgumentResolver;
import com.he.security.web.reactive.result.CurrentSecurityContextArgumentResolver;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.expression.BeanFactoryResolver;
import org.springframework.core.ReactiveAdapterRegistry;
import org.springframework.web.reactive.config.WebFluxConfigurer;
import org.springframework.web.reactive.result.method.annotation.ArgumentResolverConfigurer;

@Configuration(proxyBeanMethods = false)
public class ServerHttpSecurityConfiguration {
    private static final String BEAN_NAME_PREFIX = "com.he.security.config.annotation.web.reactive.HttpSecurityConfiguration.";
    private static final String HTTPSECURITY_BEAN_NAME = BEAN_NAME_PREFIX + "httpSecurity";

    private ReactiveAdapterRegistry adapterRegistry = new ReactiveAdapterRegistry();

    @Autowired(required = false)
    private BeanFactory beanFactory;

    @Bean
    public WebFluxConfigurer authenticationPrincipalArgumentResolverConfigurer(AuthenticationPrincipalArgumentResolver authenticationPrincipalArgumentResolver) {
        return new WebFluxConfigurer() {
            @Override
            public void configureArgumentResolvers(ArgumentResolverConfigurer configurer) {
                configurer.addCustomResolver(authenticationPrincipalArgumentResolver);
            }
        };
    }

    @Bean
    public AuthenticationPrincipalArgumentResolver authenticationPrincipalArgumentResolver() {
        AuthenticationPrincipalArgumentResolver resolver = new AuthenticationPrincipalArgumentResolver(this.adapterRegistry);
        if (this.beanFactory != null) {
            resolver.setBeanResolver(new BeanFactoryResolver(this.beanFactory));
        }
        return resolver;
    }

    @Bean
    public CurrentSecurityContextArgumentResolver reactiveCurrentSecurityContextArgumentResolver() {
        CurrentSecurityContextArgumentResolver resolver = new CurrentSecurityContextArgumentResolver(this.adapterRegistry);
        if(this.beanFactory!=null){
            resolver.setBeanResolver(new BeanFactoryResolver(this.beanFactory));
        }
        return resolver;
    }


}
